package com.aaa.vegetablemarketexpress.controller;

import com.aaa.vegetablemarketexpress.entity.*;
import com.aaa.vegetablemarketexpress.service.ShopCustomerService;
import com.aaa.vegetablemarketexpress.service.ShopService;
import com.aaa.vegetablemarketexpress.service.UserService;
import com.aaa.vegetablemarketexpress.util.OssUtil;
import com.aaa.vegetablemarketexpress.util.Page;
import com.aaa.vegetablemarketexpress.util.Result;
import com.aaa.vegetablemarketexpress.util.ResultUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.ui.Model;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @FileName: ShopController
 * @Description: 店铺控制器
 * @Author: qxh
 * @CreateTime: 2025/9/10
 * @Version: 1.0.0
 */
@RestController
@RequestMapping("/shop")
@Log4j2
public class ShopController {

    @Resource
    private ShopService shopService;
    @Resource
    private UserService userService;
    @Resource
    private ShopCustomerService shopCustomerService;

    // 在类中添加属性
 /*   @Value("${file.upload.business-licence-path}")
    private String businessLicenceSavePath;
    @Value("${file.upload.shopLogo-path}")
    private String shopLogoSavePath;
    @Value("${file.access.prefix}")
    private String fileAccessPrefix;*/

    /**
     * 查询店铺信息
     *
     * @param shopId
     * @return
     */
    @PostMapping("selectShopById")
    public Result selectShopById(Long shopId) {
        log.info("查询店铺信息");
        return ResultUtil.success(shopService.selectShopById(shopId));
    }

    /**
     * 查询店铺列表
     *
     * @param page
     * @return
     */
    @PostMapping("selectShopList")
    public Result selectShopList(@RequestBody Page<Shop> page) {
        log.info("查询店铺列表");
        return ResultUtil.success(shopService.selectShopList(page));
    }

    /**
     * 添加店铺
     *
     * @param shop
     * @return
     */
    @PostMapping("insertShop")
    public Result insertShop(@RequestBody Shop shop) {
        log.info("添加店铺");
        try {
            Shop result = shopService.insertShop(shop);
            return ResultUtil.success(result);
        } catch (Exception e) {
            log.error("添加店铺失败", e);
            return ResultUtil.failed("添加店铺失败: " + e.getMessage());
        }
    }

    /**
     * 修改店铺
     *
     * @param shop
     * @return
     */
    @PostMapping("updateShop")
    public Result updateShop(@RequestBody Shop shop) {
        log.info("修改店铺");
        try {
            int result = shopService.updateShop(shop);
            if (result > 0) {
                return ResultUtil.success("修改店铺成功");
            } else {
                return ResultUtil.failed("修改店铺失败");
            }
        } catch (Exception e) {
            log.error("修改店铺失败", e);
            return ResultUtil.failed("修改店铺失败: " + e.getMessage());
        }
    }

    /**
     * 删除店铺
     *
     * @param shopId
     * @return
     */
    @DeleteMapping("deleteShopById")
    public Result deleteShopById(Long shopId) {
        log.info("删除店铺");
        try {
            int result = shopService.deleteShopById(shopId);
            if (result > 0) {
                return ResultUtil.success("删除店铺成功");
            } else {
                return ResultUtil.failed("删除店铺失败");
            }
        } catch (Exception e) {
            log.error("删除店铺失败", e);
            return ResultUtil.failed("删除店铺失败: " + e.getMessage());
        }
    }

    /**
     * 检查店铺名称是否唯一
     *
     * @param shop
     * @return
     */
    @PostMapping("checkShopNameUnique")
    public Result checkShopNameUnique(@RequestBody Shop shop) {
        log.info("检查店铺名称是否唯一");
        return ResultUtil.success(shopService.checkShopNameUnique(shop));
    }

    /**
     * 审核店铺
     *
     * @param shop
     * @return
     */
    @PostMapping("auditShop")
    public Result auditShop(@RequestBody Shop shop) {
        log.info("审核店铺，店铺ID: {}", shop.getShopId());
        try {
            int result = shopService.auditShop(shop);
            if (result > 0) {
                log.info("店铺审核成功，店铺ID: {}", shop.getShopId());
                return ResultUtil.success("店铺审核成功");
            } else {
                log.warn("店铺审核失败");
                return ResultUtil.failed("店铺审核失败");
            }
        } catch (Exception e) {
            log.error("店铺审核时发生异常", e);
            return ResultUtil.failed("店铺审核失败: " + e.getMessage());
        }
    }

    /**
     * 上传营业执照
     *
     * @param file
     * @return
     */
   /* @PostMapping("/uploadBusinessLicence")
    public Result uploadBusinessLicence(@RequestParam("file") MultipartFile file) {
        // 获取项目根路径并构建保存路径
        String projectPath = System.getProperty("user.dir");
        String fullPath = projectPath + "/" + businessLicenceSavePath;

        if (file.isEmpty()) {
            return ResultUtil.failed("上传文件为空");
        }

        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || (!originalFilename.endsWith(".jpg") && !originalFilename.endsWith(".png"))) {
            return ResultUtil.failed("上传文件格式错误");
        }

        // 检查文件大小（不超过2MB）
        if (file.getSize() > 2 * 1024 * 1024) {
            return ResultUtil.failed("上传文件过大");
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + "_" + originalFilename;

        try {
            // 创建目录（如果不存在）
            Path path = Paths.get(fullPath);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
            }

            // 保存文件
            Path filePath = Paths.get(fullPath + fileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 构造访问URL
            String accessUrl = fileAccessPrefix + "business-licence/" + fileName;

            // 返回结果
            Map<String, Object> result = new HashMap<>();
            Map<String, String> data = new HashMap<>();
            data.put("url", accessUrl);
            result.put("url", accessUrl);
            result.put("data", data);

            log.info("营业执照上传成功，文件名：{}", fileName);

            return ResultUtil.success(result);
        } catch (Exception e) {
            log.error("营业执照上传失败", e);
            return ResultUtil.failed("营业执照上传失败: " + e.getMessage());
        }
    }*/

    /**
     * 获取当前登录商家的店铺
     */
    @GetMapping("/getMyShop")
    public Result getMyShop(HttpSession session) {
        log.info("获取当前登录商家的店铺");
        // 1. 从Session中获取当前登录用户
        User currentUser = (User) session.getAttribute("userInfo");
        if (currentUser == null) {
            return ResultUtil.failed("用户未登录");
        }

        // 2. 检查用户是否为“商家”角色
        boolean isMerchant = userService.isMerchant(currentUser.getUserId());
        if (!isMerchant) {
            return ResultUtil.failed("当前用户不是商家，无法获取店铺");
        }

        // 3. 查询商家关联的店铺（假设商家与店铺是一对一，用user_id关联）
        Shop merchantShop = shopService.getShopByUserId(currentUser.getUserId());
        if (merchantShop == null) {
            return ResultUtil.failed("该商家未关联店铺");
        }

        return ResultUtil.success(merchantShop);
    }

    /**
     * 上传店铺logo
     *
     * @param file
     * @return
     */
    /*@PostMapping("/uploadShopLogo")
    public Result uploadShopLogo(@RequestParam("file") MultipartFile file) {
        // 获取项目根路径并构建保存路径
        String projectPath = System.getProperty("user.dir");
        String fullPath = projectPath + "/" + shopLogoSavePath;

        if (file.isEmpty()) {
            return ResultUtil.failed("上传文件为空");
        }

        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || (!originalFilename.endsWith(".jpg") && !originalFilename.endsWith(".png"))) {
            return ResultUtil.failed("上传文件格式错误");
        }

        // 检查文件大小（不超过2MB）
        if (file.getSize() > 2 * 1024 * 1024) {
            return ResultUtil.failed("上传文件过大");
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + "_" + originalFilename;

        try {
            // 创建目录（如果不存在）
            Path path = Paths.get(fullPath);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
            }

            // 保存文件
            Path filePath = Paths.get(fullPath + fileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 构造访问URL
            String accessUrl = fileAccessPrefix + "shopLogo/" + fileName;

            // 返回结果
            Map<String, Object> result = new HashMap<>();
            Map<String, String> data = new HashMap<>();
            data.put("url", accessUrl);
            result.put("url", accessUrl);
            result.put("data", data);

            log.info("店铺logo上传成功，文件名：{}", fileName);

            return ResultUtil.success(result);
        } catch (Exception e) {
            log.error("店铺logo上传失败", e);
            return ResultUtil.failed("店铺logo上传失败: " + e.getMessage());
        }
    }*/

    /**
     * 店铺审核成功列表
     * @param page
     * @return
     */
    @PostMapping("selectShopListAuditStatus")
    public Result selectShopListAuditStatus(@RequestBody Page<Shop> page) {
        return ResultUtil.success(shopService.selectShopListAuditStatus(page));
    }

    @GetMapping("list")
    public Result getShopList(Model model) {
        List<Shop> shopList = shopService.getAllShops();
        model.addAttribute("shopList", shopList);
        return ResultUtil.success(shopList);
    }

    @GetMapping("statusCount")
    @ResponseBody
    public List<ShopStatusCount> getShopStatusCount() {
        return shopService.getShopStatusCount();
    }

    @GetMapping("auditStatusCount")
    @ResponseBody
    public List<ShopAuditStatusCount> getShopAuditStatusCount() {
        return shopService.getShopAuditStatusCount();
    }
    @GetMapping("getShopCount")
    public Result getShopCount() {
        Long count = shopService.countShops();
        return ResultUtil.success(count);
    }
    /**
     * 营业执照
     * @param file
     * @return
     */
    @PostMapping("/uploadBusinessLicenceImage")
    public Result uploadBusinessLicenceImage(@RequestParam("pic") MultipartFile file) {
        //调用工具类，进行上传
        return ResultUtil.success(OssUtil.uploadFile("businessLicence/images",file));
    }
    /**
     * 上传店铺Logo
     * @param file
     * @return
     */
    @PostMapping("/uploadShopLogoImage")
    public Result uploadShopLogoImage(@RequestParam("pic") MultipartFile file) {
        //调用工具类，进行上传
        return ResultUtil.success(OssUtil.uploadFile("shopLogo/images",file));
    }
}
